package lrg10002.plugins.akperms;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class PermsLoader {

        public File pLocation;
        public LoggingRecord log = new LoggingRecord("permission loading");
        public AKPermsPlugin parent;
        public HashMap<String, List<HashMap<String, Object>>> perms = new HashMap<String, List<HashMap<String, Object>>>();

        public PermsLoader(AKPermsPlugin parent, File p) {
                pLocation = p;
                this.parent = parent;
        }

        public void load() throws Exception {
                SAXBuilder bd = new SAXBuilder();
                Document d = (Document) bd.build(pLocation);
                List<Content> conts = d.getContent();
                Iterator iterator = conts.iterator();

                while (iterator.hasNext()) {
                        Element e = (Element) iterator.next();
                        ElementType et = XMLHelper.getType(e); //what type of element is it?
                        if (et == ElementType.NULL) { //if it's not one we know, go forward to the next.
                                log.addMessage("Found unreadable tag \"" + e.getName() + "\"!");
                                continue;
                        }
                        //can tag be top level?
                        if (!et.element.canBeChildOf(ElementType.NULL)) {
                                log.addMessage("The " + et.name + " tag cannot be top level!");
                                continue;
                        }

                       et.element.readElement(e);
                       if (e.getChildren().size() > 0) {
                    	   loadChildren(e);
                       }
                       
                        
                }
        }

        public void loadChildren(Element parent) {
        	ElementType parentType = XMLHelper.getType(parent);
        	for (Element child : parent.getChildren()) {
        		ElementType et = XMLHelper.getType(child);
        		if (et == ElementType.NULL){
        			log.addMessage("Found unreadable tag \"" + child.getName() + "\"!");
        			continue;
        		}
        		if (!et.element.canBeChildOf(parentType)) {
        			log.addMessage(String.format("The %s tag cannot be a child of the %s tag!", et.name, parentType.name));
                    continue;
        		}
        		if (!et.element.valElement(child)) {
        			log.addMessage(String.format("The %s tag does not allow its current placement!", et.name));
        			continue;
        		}
        		et.element.readElement(child);
        		if (child.getChildren().size() > 0) {
        			loadChildren(child);
        		}
        	}
        }
        
}